package com.feihong.txgw.ui.activity.user;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.Toast;

import com.feihong.txgw.R;
import com.feihong.txgw.adapter.SharePlatformAdapter;
import com.feihong.txgw.http.Host;
import com.feihong.txgw.inter.listener.share.ShareTypeListener;
import com.feihong.txgw.model.bean.share.SharePlatformEntity;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.utils.helper.RxHelper;
import com.feihong.txgw.utils.manage.RetrofitManager;
import com.feihong.txgw.utils.sign.SignToken;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * @name txgw_app
 * @class name：com.feihong.txgw.ui.activity.user
 * @class describe:
 * @author wangziheng
 * @time 2017/9/14 18:44
 * @change
 * @chang time
 * @class describe
 */
@RuntimePermissions
public class ShareActivity extends Activity implements ShareTypeListener {

    public static final String IS_LOGING = "is_login";
    public static final String LOGIN = "login";
    public static final String LOGOUT = "logout";
    private String shareUrl = "";
    private HashMap<String, String> signMap;
    private RecyclerView mShareLayout;
    private ArrayList<SharePlatformEntity> mPlatForms;
    private SharePlatformEntity mSharePlatFrom;
    public static final String TXGW_QQ_SHARE = "QQ";
    public static final String TXGW_QZONG_SHARE = "QZONE";
    public static final String TXGW_WECHATE_SHARE = "WECHAT";
    public static final String TXGW_WXCIRCLE_SHARE = "WXCIRCLE";
    public static final String TXGW_SMS_SHARE = "SMS";

    private final String TAG = "通讯顾问";
    private String[] platform = new String[]{"QQ", "QQ空间", "微信", "微信朋友圈","短信"};
    private String[] platformType = {TXGW_QQ_SHARE, TXGW_QZONG_SHARE, TXGW_WECHATE_SHARE, TXGW_WXCIRCLE_SHARE,TXGW_SMS_SHARE};
    private int[] platformImg = {R.mipmap.icon_qq, R.mipmap.qzone_share, R.mipmap.weixin_share, R.mipmap.wxcircle_share,R.mipmap.sms_share};
    private Drawable mShareBitmap;
    private SharePlatformAdapter mAdapter;

    private GridLayoutManager gridLayoutManager;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_share_share);
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        initView();
        initData();
//        ShareActivityPermissionsDispatcher.queryImgFileWithCheck(this);
    }

    private int requestNum = 0;

    private void initView() {
        gridLayoutManager = new GridLayoutManager(this, 4);
        mUmShareApi = UMShareAPI.get(this);
        mAdapter = new SharePlatformAdapter(this);
        mShareLayout = (RecyclerView) findViewById(R.id.share_platform_recyclerview);
        mShareLayout.setLayoutManager(gridLayoutManager);
        mShareLayout.setAdapter(mAdapter);
        if (getIntent().getStringExtra(IS_LOGING).equals(LOGIN)) {
            signMap = new HashMap<>();
            shareUrl = Host.HTTP_HOME + "App/Invitation/index.html?" + new SignToken().setSigen(signMap);
            web = new UMWeb(shareUrl);
        } else {
            shareUrl = Host.HTTP_HOME + "App/Invitation/invit_ok";
            web = new UMWeb(shareUrl);
        }
//        UMImage umImage = new UMImage(this,"http://txgwimg.djlm.wang/img/2017/09/20/1505882409H9208240940170d.png");
        UMImage umImage = new UMImage(this, R.mipmap.share_content_icon);
        //质量压缩，适合长图的分享
        umImage.compressStyle = UMImage.CompressStyle.SCALE;
        web.setTitle("通讯100");
        web.setThumb(umImage);
        web.setDescription("通讯100");
        querySMSurl();

        mPlatForms = new ArrayList<>();
        for (int i = 0; i < platform.length; i++) {
            mSharePlatFrom = new SharePlatformEntity();
            mSharePlatFrom.setmPlatformName(platform[i]);
            mSharePlatFrom.setmPlatformType(platformType[i]);
            mShareBitmap = getResources().getDrawable(platformImg[i]);
            mSharePlatFrom.setmPlatfromImg(mShareBitmap);
            mPlatForms.add(mSharePlatFrom);
        }
        mAdapter.setPlatform(mPlatForms);
    }

    private String mSmsUrl;

    private void querySMSurl() {
        RetrofitManager.getInstance().getSMSUrl(UserLoginInfo.getUserId()).compose(RxHelper.<String>rxSchedulerHelper())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String result) {
                        requestNum++;
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            if ("200".equals(jsonObject.optString("code"))) {
                                JSONObject urlJsonObject = jsonObject.optJSONObject("data");
                                mSmsUrl = urlJsonObject.optString("url");
                            } else {
                                if (requestNum < 3) {
                                    querySMSurl();
                                } else {
                                    Toast.makeText(ShareActivity.this, "请求服务器失败", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (JSONException e) {
                            Toast.makeText(ShareActivity.this, "解析数据失败", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                        Toast.makeText(ShareActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    private void initData() {
        mAdapter.setOnShareListener(this);

    }

    private UMWeb web;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
//            Toast.makeText(ShareActivity.this,"成功了",Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {

        }
    };

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        overridePendingTransition(R.anim.alpha_in,R.anim.alpha_out);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        finish();
        overridePendingTransition(R.anim.alpha_in,R.anim.alpha_out);
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
    }

    @Override
    public void setOnShareItemListener(SharePlatformEntity flatformInfo) {
        checkFlatformType(flatformInfo);
    }

    private UMShareAPI mUmShareApi;

    private void checkFlatformType(SharePlatformEntity shareType) {
        switch (shareType.getmPlatformType()) {
            case TXGW_QQ_SHARE:
                if (isAgree) {
                    if (mUmShareApi.isInstall(this, SHARE_MEDIA.QQ)) {
                        startShare(SHARE_MEDIA.QQ.toSnsPlatform().mPlatform);
                    } else {
                        Toast.makeText(this, "未安装qq客户端", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    ShareActivityPermissionsDispatcher.queryImgFileWithCheck(this);
                }
                break;
            case TXGW_QZONG_SHARE:
                if (mUmShareApi.isInstall(this, SHARE_MEDIA.QZONE)) {
                    startShare(SHARE_MEDIA.QZONE.toSnsPlatform().mPlatform);
                } else {
                    Toast.makeText(this, "未安装qzone客户端", Toast.LENGTH_SHORT).show();
                }
                break;
            case TXGW_WECHATE_SHARE:
                if (mUmShareApi.isInstall(this, SHARE_MEDIA.WEIXIN)) {
                    startShare(SHARE_MEDIA.WEIXIN.toSnsPlatform().mPlatform);
                } else {
                    Toast.makeText(this, "未安装微信客户端", Toast.LENGTH_SHORT).show();
                }
                break;
            case TXGW_WXCIRCLE_SHARE:
                if (mUmShareApi.isInstall(this, SHARE_MEDIA.WEIXIN_CIRCLE)) {
                    startShare(SHARE_MEDIA.WEIXIN_CIRCLE.toSnsPlatform().mPlatform);
                } else {
                    Toast.makeText(this, "未安装微信客户端", Toast.LENGTH_SHORT).show();
                }
                break;
            case TXGW_SMS_SHARE:
                if(TextUtils.isEmpty(mSmsUrl)){
                    Toast.makeText(this, "请检查网络", Toast.LENGTH_SHORT).show();
                }else {
                    new ShareAction(ShareActivity.this)
                            .setPlatform(SHARE_MEDIA.SMS)
                            .withText(mSmsUrl)
                            .setCallback(shareListener).share();
                }
                break;
            default:break;
        }
    }

    private void startShare(SHARE_MEDIA platform) {
        new ShareAction(ShareActivity.this)
                .setPlatform(platform)
                .withMedia(web)
                .setCallback(shareListener).share();
    }

    private boolean isAgree = false;

    @NeedsPermission({android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE})
    void queryImgFile() {
        isAgree = true;
    }

    @OnPermissionDenied({android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE})
    void queryImgFileDenied() {
        isAgree = false;
//        Toast.makeText(this,"")
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ShareActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE})
    public void rationaleQueryImg(final PermissionRequest request) {
        request.proceed();
//        new AlertDialog.Builder(this)
//                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(@NonNull DialogInterface dialog, int which) {
//                        request.proceed();
//                    }
//                })
//                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(@NonNull DialogInterface dialog, int which) {
//                        request.cancel();
//                    }
//                })
//                .setCancelable(false)
//                .setMessage("请允许读取本地数据权限")
//                .show();
    }
}
